package cn.wolfcode.shop.cloud.mq;

import cn.wolfcode.shop.cloud.domain.OrderInfo;
import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfcode.shop.cloud.service.ISeckillGoodService;
import cn.wolfcode.shop.cloud.service.RedisService;
import cn.wolfcode.shop.cloud.util.SeckillKeyPrefix;
import cn.wolfcode.shop.cloud.vo.SeckillGoodVO;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@RocketMQMessageListener(
        consumerGroup = MQConstans.CREATE_ORDER_DELAY_GROUP,
        topic = MQConstans.CREATE_ORDER,
        selectorExpression = MQConstans.CREATE_ORDER_DELAY_TAG
)
@Component
public class OrderSuccessDelayMQListener implements RocketMQListener<Map> {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private ISeckillGoodService seckillGoodService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(Map map) {
        System.out.println("进入延时消息+发送广播消息");
        Object seckillId = map.get("seckillId");
        //把seckillId转化为long类型
        Long goodId = null;
        if (seckillId instanceof Long) {
            goodId = (Long) seckillId;
        } else if (seckillId instanceof Integer) {
            goodId = ((Integer) seckillId).longValue();
        }
        //修改订单的状态为，超时未支付 wherer STATUS_ARREARAGE：未付款 为 STATUS_TIMEOUT 超时未支付
        //获取订单号
        String orderNo = (String) map.get("data");
        int count = orderInfoService.changeOrderINfoStatus(orderNo, OrderInfo.STATUS_TIMEOUT);
        if (count != 0) {
            //count != 0（有影响行）说明未付款
            //未付款：回补真实库存/预库存/本地标识
            //真实库存要加回去
           seckillGoodService.incrStockCount(goodId);
            //回补预库存 (写一个方法处理)
            seckillGoodService.incrRedisStockCount(goodId);

            //发送广播消息修改本地标识
          rocketMQTemplate.syncSend(MQConstans.CREATE_ORDER_FLAG_DEST,goodId);


        }


    }
}
